import { TimeUtils } from "./timeUtils";
import SoundChannel from "../libs/sounds";

export class Record {
    constructor() {
        this.state = false;
        this.list = [];
        this.endTime = null;
    }

    size() {
        return this.list.length;
    }

    start() {
        this.state = true;
        this.startTime = new Date().getTime();
    }

    stop() {
        this.state = false;
        this.endTime = new Date().getTime();
    }

    startSelect({ dots, value }) {
        this.list.push({
            dots,
            value,
            start: new Date().getTime(),
            select: null,
            end: null,
            correct: null
        });
    }

    selectEnd(select) {
        let r = this.list[this.list.length - 1];
        if (r) {
            Object.assign(r, {
                end: new Date().getTime(),
                select,
                correct: r.value == select
            });
            new SoundChannel().play(r.value == select ? 'correct' : 'wrong');
        }
    }

    reStart() {
        this.state = false;
        this.list = [];
        this.endTime = null;
    }

    getStatistic() {
        let total = this.list.filter(a => a.correct != null).length;
        let correct = this.list.filter(a => a.correct == true).length;
        let wrong = this.list.filter(a => a.correct == false).length;

        return {
            total,
            correct,
            wrong,
            lastTime: TimeUtils.formatOffset((this.endTime ? this.endTime : new Date().getTime()) - this.startTime),
            correctPercent: Math.round((correct / total) * 100),
            avgPercent: TimeUtils.formatOffset(this.list.map(a => a.end - a.start).reduce((a, b) => a + b, 0) / this.list.length)
        }
    }
}